package com.bishe.controller;

import cn.hutool.core.util.StrUtil;
import com.bishe.pojo.Checkwork;
import com.bishe.pojo.Message;
import com.bishe.pojo.QueryModel;
import com.bishe.serivce.IMessageService;
import com.bishe.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 消息控制层
 *
 * @date 2022/03/20 42:08:24
 */
@RestController
@RequestMapping("/message")
@Api(tags = "消息控制器")
@CrossOrigin
public class MessageController {
    @Autowired
    private IMessageService messageService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @ApiOperation("添加和修改消息")
    @PostMapping("/addOrUpdate")
    public Result addOrUpdate(@RequestBody Message message, HttpServletRequest httpServletRequest) {
        //检查admin登录
        JobUtil.checkAdminLogin(httpServletRequest,jdbcTemplate);
        if (message == null) {
            throw new EcoBootException("message 为空！");
        }
        messageService.addOrUpdate(message, httpServletRequest);

        return Result.ok();
    }

    @ApiOperation("删除消息")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") String id,HttpServletRequest request) {
        //检查admin登录
        JobUtil.checkAdminLogin(request,jdbcTemplate);

        messageService.deleteById(id);

        return Result.ok();
    }


    @ApiOperation("消息分页 标题模糊")
    @GetMapping("/getPage")
    public Result getPage(QueryModel queryModel,HttpServletRequest request) {

        List<Message> data = null;
        Integer pageNo = queryModel.getPageNo();
        Integer pageSize = queryModel.getPageSize();
        String searchTxt = queryModel.getSearchTxt();
        SqlQueryUtils<Message> applySqlQueryUtils = new SqlQueryUtils<Message>(Message.class, jdbcTemplate);

        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        if (StrUtil.isNotEmpty(searchTxt)) {
            applySqlQueryUtils.like(Message::getTitle, searchTxt);
        }
        //创建时间倒叙
        applySqlQueryUtils.orderByDesc(Message::getCreateTime);
        //都是0 不分页
        if (pageNo == 0 && pageSize == 0) {
            data = applySqlQueryUtils.getList();
        } else {
            data = applySqlQueryUtils.limit(pageNo, pageSize).getList();
        }

        return Result.ok(new PageResult<Message>(queryModel, applySqlQueryUtils, data));
    }


}
